package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.consts.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.vo.LoginRespVo;
import com.atguigu.gmall.model.user.vo.LoginVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.model.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author lyd
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2025-03-21 20:19:52
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public LoginRespVo login(LoginVo loginVo, String deviceId) {
        //1.校验用户名密码是否为空
        if (StringUtils.isEmpty(loginVo.getLoginName()) || StringUtils.isEmpty(loginVo.getPasswd())) {
            throw new GmallException(ResultCodeEnum.LOGIN_PASSWORD_USERNAME_NOT_EMPTY);
        }
        UserInfo userInfo = this.lambdaQuery()
                .eq(UserInfo::getLoginName, loginVo.getLoginName())
                .eq(UserInfo::getPasswd, MD5.encrypt(loginVo.getPasswd()))
                .one();
        //2、判断用户是否存在
        if (userInfo == null) {
            throw new GmallException(ResultCodeEnum.LOGIN_NOT_EXIST);
        }
        //3、将用户信息保存在redis,返回token
        String token = UUID.randomUUID().toString().replace("-", "");
        userInfo.setDeviceId(deviceId);
        redisTemplate.opsForValue().set(RedisConst.LOGIN_USER+token, JsonUtil.objToJsonStr(userInfo),7, TimeUnit.DAYS);
        LoginRespVo loginRespVo = new LoginRespVo();
        loginRespVo.setToken(token);
        loginRespVo.setNickName(userInfo.getNickName());
        loginRespVo.setUserId(userInfo.getId());
        loginRespVo.setName(userInfo.getName());
        return loginRespVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER+token);
    }
}




